<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>用药记录</h2>
          <el-form :inline="true" :model="searchForm" ref="searchFormRef">
            <el-form-item label="用药时间" prop="dateRange">
              <div style="display: flex; gap: 10px;">
                <el-date-picker
                    v-model="searchForm.startTime"
                    type="date"
                    placeholder="开始日期"
                    value-format="YYYY-MM-DD"
                    :max-date="searchForm.endTime"
                />
                <span style="align-self: center">至</span>
                <el-date-picker
                    v-model="searchForm.endTime"
                    type="date"
                    placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    :min-date="searchForm.startTime"
                />
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
              <el-button
                  type="primary"
                  icon="el-icon-plus"
                  @click="showFormDialog = true"
              >
                新增用药记录
              </el-button>
            </el-form-item>



          </el-form>
        </div>
      </template>

      <el-table :data="medicationData" border stripe v-loading="loading" element-loading-text="数据加载中..." element-loading-background="rgba(255, 255, 255, 0.8)">
        <el-table-column prop="medicationTime" label="用药时间" width="180"></el-table-column>
        <el-table-column prop="elderName" label="老人名称"></el-table-column>
        <el-table-column prop="name" label="药品名称"></el-table-column>
        <el-table-column prop="dosage" label="剂量"></el-table-column>
      </el-table>

      <div style="margin-top: 20px">
        <el-pagination
            @current-change="currentChange"
            @size-change="sizeChange"
            :page-size="pageInfo.pageSize"
            :current-page="pageInfo.pageNum"
            background
            layout="total,sizes, prev, pager, next"
            :total="pageInfo.total">
        </el-pagination>

        <!-- 新增记录弹窗 -->
        <el-dialog
            title="新增用药记录"
            v-model="showFormDialog"
            width="600px"
            @closed="resetForm"
        >
          <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
            <el-form-item label="老人姓名" required>
              <el-select
                  v-model="form.elderId"
                  placeholder="请选择老人"
                  style="width: 100%"
              >
                <el-option
                    v-for="elder in elderList"
                    :key="elder.id"
                    :label="elder.nickname"
                    :value="elder.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="药品名称" required>
              <el-input
                  v-model="form.name"
                  placeholder="请输入药品全称"
                  maxlength="100"
                  show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item label="用药时间" required>
              <el-date-picker
                  v-model="form.medicationTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm"
                  :editable="false"
                  :clearable="false"
                  style="width: 100%"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="用药详情" required>
              <el-input
                  v-model="form.dosage"
                  type="textarea"
                  :rows="3"
                  placeholder="格式：每次剂量+用药频率，例：每次10mg，每日3次"
                  maxlength="255"
                  show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                  type="primary"
                  @click="submit"
                  style="width: 200px"
              >提交记录</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import http from '@/utils/http.js'
import utils from "@/utils/tools.js";
import { ElMessage } from 'element-plus'
import dayjs from "dayjs";

const medicationData = ref([])
const pageInfo = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const showFormDialog = ref(false)

const elderList = ref([])

const loading = ref(false)

const searchForm = reactive({
  startTime: '',
  endTime: ''
})

const form = ref({
  elderId: '',
  name: '',
  medicationTime: '',
  dosage: '',
})

const formRef = ref(null)

const rules = {
  elderId: [{ required: true, message: '请选择老人', trigger: 'change' }],
  name: [
    { required: true, message: '请输入药品名称', trigger: 'blur' },
    { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
  ],
  dosage: [
    { required: true, message: '请输入用药详情', trigger: 'blur' },
    { max: 255, message: '长度不能超过255个字符', trigger: 'blur' }
  ],
  medicationTime: [{ required: true, message: '请选择用药时间', trigger: 'change' }]
}

const searchFormRef = ref()

onMounted(async () => {
  await getElderList()
  await getMedicationList()
})

async function getElderList() {
  try {
    const staff = await http.get(`/staff/selectById/${utils.getCurrentUser().id}`)
    if (staff.data) {
      const buildingId = staff.data.buildingId
      const res = await http.get(`/elder/selectByBuildingId/${buildingId}`)
      elderList.value = res.data
    }
  } catch (e) {
    if (e.response?.status !== 404) {
      ElMessage.error('获取数据失败')
    }
  }
}

async function getMedicationList() {
  loading.value = true
  try {
    const params = {
      pageNum: pageInfo.value.pageNum,
      pageSize: pageInfo.value.pageSize,
      staffId: utils.getCurrentUser().id,
      medicationStartTime: searchForm.startTime,
      medicationEndTime: searchForm.endTime
    }
    const res = await http.get('/medicationRecord/page', { params })
    medicationData.value = res.data.list
    pageInfo.value.total = res.data.total
  } catch (e) {
    console.error('获取用药记录失败:', e)
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

const submit = () => {
  formRef.value.validate(valid => {
    if (!valid) return
    
    // 强制类型转换和时间格式化
    const formattedTime = form.value.medicationTime ?
      dayjs(form.value.medicationTime).format('YYYY-MM-DD HH:mm:ss') :
      null

    http.post('/medicationRecord/add', {
      ...form.value,
      medicationTime: formattedTime,
      staffId: utils.getCurrentUser().id
    }).then(() => {
      ElMessage.success('记录提交成功')
      getMedicationList()
      showFormDialog.value = false
    }).catch(e => {
      console.error('完整错误信息:', e.response?.data || e.message)
      ElMessage.error(e.response?.data?.message || '提交失败')
    })
  })
}

function currentChange(e) {
  pageInfo.value.pageNum = e
  getMedicationList()
}

function sizeChange(e) {
  pageInfo.value.pageSize = e
  getMedicationList()
}

function search() {
  pageInfo.value.pageNum = 1
  getMedicationList()
}

function resetSearch() {
  searchFormRef.value.resetFields()
  searchForm.startTime = ''
  searchForm.endTime = ''
  getMedicationList()
}

onMounted(() => {
  getMedicationList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}
</style>


